package com.example.testproj;

import android.content.Context;
import android.graphics.Color;
import android.support.v4.widget.TextViewCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


/**
 * @user xie
 * @date 2019/2/21 0021
 * @email 773675907@qq.com.
 */

public class CanEditView extends RelativeLayout {

    private ImageView deleteView;
    private ImageView changeSizeView;
    private View view;
    private View view1;
    private int lastY;
    private int lastX;
    private static final String TAG = "CanEditView";

    boolean isChangeSize = false; //是否点击了改变大小的区域

    boolean enablePosChange = true; //是否使能改变位置

    //放大缩小用
    private int offsetHeight = 0; //高度偏移值
    private int offsetWidth = 0; //宽度偏移值

    //拖拽用
    private int offsetX = 0; //marginLeft 偏移值
    private int offsetY = 0; //marginTop的偏移值

    // 由于原程序的宽高计算问题，需要保存原始的宽高，否则会出现到达某个极限值大小胡乱变化的情况
    private int firstHeight = 0;
    private int firstWidth = 0;


    //放大缩小后，此布局的最小宽高。不能小于0
    private int minWidth = 10;
    private int minHeight = 10;

    //字体和实际所占大小的比例,例如字体大小为10，那么textview所占高度为12
    private double fontScalSize=1.2;

    //中文宽度是英文的几倍
    private float proportionCnEn=3;


    public CanEditView(Context context) {
        this(context, null);
    }

    public CanEditView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CanEditView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        deleteView = new ImageView(getContext());
        deleteView.setImageResource(R.mipmap.ic_launcher);
        addView(deleteView, 0);
        changeSizeView = new ImageView(getContext());
        changeSizeView.setImageResource(R.mipmap.ic_launcher);
        addView(changeSizeView, 1);
        view = new View(getContext());
        view.setBackgroundColor(Color.parseColor("#00ff00"));

        addView(view, 2);
        view1 = new View(getContext());
        view1.setBackgroundColor(Color.parseColor("#ff0000"));
        addView(view1, 3);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        getChildAt(0).layout(getWidth() - deleteView.getWidth(), 0, getWidth(), deleteView.getHeight());
        getChildAt(1).layout(getWidth() - changeSizeView.getWidth(), getHeight() - changeSizeView.getHeight(), getWidth(), getHeight());
        getChildAt(2).layout(deleteView.getWidth() / 2, deleteView.getHeight() / 2, getWidth() - deleteView.getWidth() / 2, getHeight() - deleteView.getHeight() / 2);
        getChildAt(3).layout(deleteView.getWidth() / 2, deleteView.getHeight() / 2, getWidth() - changeSizeView.getWidth() / 2, getHeight() - changeSizeView.getHeight() / 2);
        if (getChildAt(4) != null && getChildAt(4).getWidth() != 0) {
            getChildAt(4).layout(deleteView.getWidth() / 2, deleteView.getHeight() / 2, deleteView.getWidth() / 2 + getChildAt(4).getWidth(), deleteView.getHeight() / 2 + getChildAt(4).getHeight());
          //  TextViewCompat.setAutoSizeTextTypeWithDefaults((TextView) getChildAt(4), TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM);
           // TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration((TextView) getChildAt(4), 5, 1000, 1, TypedValue.COMPLEX_UNIT_SP);
        }

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Log.d(TAG, "onMeasure: (" + offsetWidth + "," + offsetHeight + "）");
        //如果原始宽高为0，则使用原来的宽高测绘机制，否则加上偏移值
        if (firstHeight == 0 || firstWidth == 0) {
            if (getChildAt(4) != null && getChildAt(4).getWidth() != 0) {
                int width = getChildAt(4).getWidth() + deleteView.getWidth();
                int height = getChildAt(4).getHeight() + deleteView.getHeight() / 2 + changeSizeView.getHeight() / 2;
                firstHeight = height;
                firstWidth = width;
                Log.d(TAG, "onMeasure: new");
                super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.getMode(widthMeasureSpec)), MeasureSpec.makeMeasureSpec(height, MeasureSpec.getMode(heightMeasureSpec)));
            } else {
                Log.d(TAG, "onMeasure: old" + (MeasureSpec.getSize(widthMeasureSpec)));
                firstHeight = MeasureSpec.getSize(heightMeasureSpec);
                firstWidth = MeasureSpec.getSize(widthMeasureSpec);
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();
            offsetX = layoutParams.leftMargin;
            offsetY = layoutParams.topMargin;
        } else {
            int width = firstWidth + offsetWidth;
            int height = firstHeight + offsetHeight;

            width = width < minWidth ? minWidth : width;
            height = height < minHeight ? minHeight : height;


            super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.getMode(widthMeasureSpec)), MeasureSpec.makeMeasureSpec(height, MeasureSpec.getMode(heightMeasureSpec)));
            autoSetTextSize((TextView) getChildAt(4));
        }


    }

    /**
     * 根据textview宽高，自动改变字体大小
     * @param textView
     */
    public void autoSetTextSize(final TextView textView){
        int width=textView.getMeasuredWidth();
        int height=textView.getMeasuredHeight();

        Log.d(TAG, "size: (" + width + "," + height + "）");

        String content=textView.getText().toString();

        // 将所有的非英文字符串替换成“”，即可得到英文
        String s1 = content.replaceAll("[^a-zA-Z]", "");


        // 将所有的英文字符串替换成“”，即可得到中文
        String s2 = content.replaceAll("[a-zA-Z]", "");

        Log.d(TAG, "autoSetTextSize: s1="+s1);
        Log.d(TAG, "autoSetTextSize: s2="+s2);

        float contentLength=s1.length()/proportionCnEn+s2.length();
        float contextSize=width<height?width:height;
        for (;contextSize>0;contextSize=contextSize-1){
            int widthLength= (int) (width/(contextSize*fontScalSize));
            int heightLength= (int) (height/(contextSize*fontScalSize));
           // Log.d(TAG, "widthLength: (" + widthLength + "," + heightLength + "）"+contextSize);
            if (contentLength<=(widthLength*heightLength)){
                break;
            }
        }
        Log.d(TAG, "run: 刷新字体大小"+contextSize);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, contextSize);


    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    private boolean isChange;

    public boolean isChangeSize(float x, float y) {
        if ((x >= (getWidth() - changeSizeView.getWidth())) && (y >= (getHeight() - changeSizeView.getHeight()))) {
            isChange = true;
        } else {
            isChange = false;
        }
        return isChange;
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                Log.d(TAG, "onTouchEvent: 点击");
                lastY = (int) event.getRawY();
                lastX = (int) event.getRawX();

                float localY = event.getY();
                float localX = event.getX();
                if (localX > (getWidth() - changeSizeView.getWidth()) && localY > (getHeight() - changeSizeView.getHeight())) {
                    Log.d(TAG, "onTouchEvent: 触摸的是改变大小的view");
                    isChangeSize = true;
                } else {
                    isChangeSize = false;
                }
                Log.d(TAG, "onTouchEvent: " + localY);
                Log.d(TAG, "onTouchEvent: " + localX);
                break;
            case MotionEvent.ACTION_UP:
                Log.d(TAG, "onTouchEvent: 抬起");
                break;
            case MotionEvent.ACTION_MOVE:
                //  Log.d(TAG, "onTouchEvent: 移动");
                int tempRawX = (int) event.getRawX();
                int tempRawY = (int) event.getRawY();

                int dx = tempRawX - lastX;
                int dy = tempRawY - lastY;
                lastX = tempRawX;
                lastY = tempRawY;
                if (isChangeSize) {


                    offsetHeight = offsetHeight + dy;
                    offsetWidth = offsetWidth + dx;

                    //为了触发view的onMeasure方法
                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();
                    setLayoutParams(layoutParams);
                } else if (enablePosChange) {

                    offsetY = offsetY + dy;
                    offsetX = offsetX + dx;

                    Log.d(TAG, "offset: (" + offsetX + "," + offsetY + "）");

                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();
                    layoutParams.setMargins(offsetX, offsetY, 0, 0);
                    setLayoutParams(layoutParams);
                }

                break;
        }
        return true;
    }

}
